package com.yeu;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Index
 */
@WebServlet("/Index")
public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Index() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /** 获取真实用户IP **/
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		} else {
			return request.getHeader("x-forwarded-for");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
		String loginState = "";//登录状态
		String userNumber = "";
		String userName = "";
		String userSex = "";
		String userAge = "";
		//String userPhone = request.getParameter("userPhone");
		String userHead = "";
		String userBirthday = "";
		String userQQ = "";
		String userEmail = "";
		String homeAddress = "";
		String introduction = "";
		String ipAddress = getRemortIP(request);
		Cookie[] mCookie = request.getCookies();
		
		
		/* 获取信息模块 */
		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
			ResultSet result;
			if (mCookie != null) {
				for (Cookie cookie : mCookie) {
					if (cookie.getName().equals("userNumber")) {
						userNumber = cookie.getValue();
					}
				}
				/*
				for (int i = 0; i < mCookie.length; i++) {
					Cookie cookie = mCookie[i];
					if (mCookie.length>=3 && i==1) {
						userNumber = cookie.getValue();
						System.out.println(cookie.getValue());
					}
				}*/
				
			}else {
				// Cookie不存在就转发
				System.err.println("不存在");
				//填写用户信息
				loginState = "                                <li><a href=\"regist.jsp\"><span class=\"glyphicon glyphicon-user\"></span>注册</a></li>\n" +
			            "                                <li><a href=\"login.jsp\"><span class=\"glyphicon glyphicon-log-in\"></span> 登录</a></li>";
				request.setAttribute("loginState", loginState);
				request.setAttribute("userName", userName);
				request.setAttribute("userNumber", userNumber);
				request.setAttribute("userHead", "head");
				request.setAttribute("userSex", userSex);
				request.setAttribute("userAge", userAge);
				request.setAttribute("userBirthday", userBirthday);
				request.setAttribute("userQQ", userQQ);
				request.setAttribute("userEmail", userEmail);
				request.setAttribute("homeAddress", homeAddress);
				request.setAttribute("introduction", introduction);
				request.getRequestDispatcher("index.jsp").forward(request, response); //此处重定向不行
				//断开数据库连接
				statement.close();
				return;
			}
						
			String sqlQuery = "select * from " + DBUtil.TABLE_USER_INFO + " where userNumber='" + userNumber + "'";
			// 查询类操作返回一个ResultSet集合，没有查到结果时ResultSet的长度为0
			result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否正确
			if (result.next() && !userNumber.equals("")) { // 已存在 result.next()
				userName = result.getString("userName");
				userSex = result.getString("userSex");
				userAge = result.getString("userAge");
				userHead = result.getString("userHead");
				userBirthday = result.getString("userBirthday");
				userQQ = result.getString("userQQ");
				userEmail = result.getString("userEmail");
				homeAddress = result.getString("homeAddress");
				introduction = result.getString("introduction");
				if (userHead == null) {
					userHead ="head";
				}
				//填写用户信息
				loginState = "<li><a href=\"Index\"><span class=\"glyphicon glyphicon-user\"></span>" + userName + "</a></li>\n" +
			            "                                <li><a href=\"Exit\"><span class=\"glyphicon glyphicon-log-in\"></span> 退出</a></li>";
				request.setAttribute("loginState", loginState);
				request.setAttribute("userName", userName);
				request.setAttribute("userNumber", userNumber);
				request.setAttribute("userHead", userHead);
				request.setAttribute("userSex", userSex);
				request.setAttribute("userAge", userAge);
				request.setAttribute("userBirthday", userBirthday);
				request.setAttribute("userQQ", userQQ);
				request.setAttribute("userEmail", userEmail);
				request.setAttribute("homeAddress", homeAddress);
				request.setAttribute("introduction", introduction);
				result.close();
				request.getRequestDispatcher("index.jsp").forward(request, response); //此处重定向不行
				
				//断开数据库连接
				statement.close();
			} else { // 帐号不存在
				//将日志信息插入日志表
				/*mLog = "帐号错误";
				String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('','','" + ipAddress + "','" + mLog + "')";
				statement.executeUpdate(sqlInsertLog); // 插入帐号密码*/
				// 帐号不存在就转发
				//填写用户信息
				loginState = "<li><a href=\"regist.jsp\"><span class=\"glyphicon glyphicon-user\"></span>注册</a></li>\n" +
			            "                                <li><a href=\"login.jsp\"><span class=\"glyphicon glyphicon-log-in\"></span> 登录</a></li>";
				request.setAttribute("loginState", loginState);
				request.setAttribute("userName", userName);
				request.setAttribute("userNumber", userNumber);
				request.setAttribute("userHead", "head");
				request.setAttribute("userSex", userSex);
				request.setAttribute("userAge", userAge);
				request.setAttribute("userBirthday", userBirthday);
				request.setAttribute("userQQ", userQQ);
				request.setAttribute("userEmail", userEmail);
				request.setAttribute("homeAddress", homeAddress);
				request.setAttribute("introduction", introduction);
				request.getRequestDispatcher("index.jsp").forward(request, response); //此处重定向不行
				
				//断开数据库连接
				statement.close();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
